<template>
  <el-dialog :visible.sync="visible" :title="!dataForm.id ? $t('add') : $t('update')" :close-on-click-modal="false" :close-on-press-escape="false" width="70%">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm"  :label-width="$i18n.locale === 'en-US' ? '120px' : '120px'">
        <el-row :gutter="20">
            <el-col :xs="24" :lg="colConfig">
          <el-form-item label="编码" v-if="dataForm.id" prop="code">
     <el-input v-model="dataForm.code"  placeholder="编码"></el-input>
</el-form-item>
                <el-form-item label="名称" prop="name">
     <el-input v-model="dataForm.name" placeholder="名称"></el-input>
</el-form-item>
                <el-form-item label="类型" prop="linkType">
                    <el-select v-model="dataForm.linkType" clearable   placeholder="请选择链接类型">
                        <el-option
                                v-for="item in linkTypeoptions"
                                :key="item.dictCode"
                                :label="item.dictName"
                                :value="item.dictCode"
                        >
                        </el-option>
                    </el-select>
</el-form-item>
                <el-form-item label="LOGO" prop="fileList">
     <el-upload
                              class="upload-demo"
                              :action="url"
                              :on-preview="handlePreview"
                              :on-remove="handleRemove"
                              :file-list="fileList"
                              :on-success="successHandle"
                              :limit='1'
                              list-type="picture"
                              :before-upload="beforeAvatarUpload"
                              >
                              <el-button size="small" type="primary">点击上传</el-button>
                              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2mb</div>
                            </el-upload>
                  </el-form-item>
                <el-form-item label="URL链接" prop="lurl">
     <el-input v-model="dataForm.lurl" placeholder="URL链接"></el-input>
</el-form-item>
                <el-form-item prop="remark" label="描述">
                    <!-- 富文本编辑器, 容器 -->
                    <div id="J_quillEditor"></div>
                    <!-- 自定义上传图片功能 (使用element upload组件) -->
                </el-form-item>
                <el-form-item label="描述" hidden prop="remark">
     <el-input v-model="dataForm.remark" placeholder="描述"></el-input>
</el-form-item>
                <el-form-item label="状态" prop="status" size="mini">
   <el-radio-group v-model="dataForm.status">
       <el-radio :label="0">停用</el-radio>
       <el-radio :label="1">正常</el-radio>
   </el-radio-group>
</el-form-item>
                            </el-col>
        </el-row>
        <el-form-item label="logoUrl" prop="logoUrl" >
            <el-input v-model="dataForm.logoUrl" placeholder="LOGO" readonly="readonly">  </el-input>
        </el-form-item>
    </el-form>
    <template slot="footer">
      <el-button @click="visible = false">{{ $t('cancel') }}</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()">{{ $t('confirm') }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
import debounce from 'lodash/debounce'
import 'quill/dist/quill.snow.css'
import Quill from 'quill'
export default {
  data () {
    return {
      quillEditor: null,
      quillEditorToolbarOptions: [
        ['bold', 'italic', 'underline', 'strike'],
        [{ 'header': 1 }, { 'header': 2 }],
        [{ 'list': 'ordered' }, { 'list': 'bullet' }],
        [{ 'script': 'sub' }, { 'script': 'super' }],
        [{ 'indent': '-1' }, { 'indent': '+1' }],
        [{ 'direction': 'rtl' }],
        [{ 'size': ['small', false, 'large', 'huge'] }],
        [{ 'header': [1, 2, 3, 4, 5, 6, false] }],
        [{ 'color': [] }, { 'background': [] }],
        [{ 'font': [] }],
        [{ 'align': [] }],
        ['clean']
      ],
      url: '',
      fileList: [],
      colConfig: 1, // 列配置 1 2列
      visible: false,
      getDicListURL: '/sys/dict/type/',
      linkTypeoptions: '',
      dataForm: {
        id: '',
        code: '',
        name: '',
        linkType: '',
        logoUrl: '',
        lurl: '',
        remark: '',
        status: 1,
        creator: '',
        createDate: '',
        updater: '',
        updateDate: ''
      }
    }
  },
  computed: {
    dataRule () {
      return {
        name: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        linkType: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        lurl: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        status: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ]

      }
    }
  },
  created () {
    this.colConfig = 24 / this.colConfig
  },
  methods: {
    init () {
      this.getLinkTypeInfo()
      this.fileList = []
      this.url = `${window.SITE_CONFIG['apiURL']}/sys/oss/fileupload?projectCode=link&projectName=网址链接信息&projectId=0&phase=0&ywTableName=bs_link_info`
      this.visible = true
      this.$nextTick(() => {
        if (this.quillEditor) {
          this.quillEditor.deleteText(0, this.quillEditor.getLength())
        } else {
          this.quillEditorHandle()
        }
        this.$refs['dataForm'].resetFields()
        if (this.dataForm.id) {
          this.getInfo()
        }
      })
    },
    // 获取链接类型
    getLinkTypeInfo () {
      this.$http.get(this.getDicListURL + 'linkType').then(({ data: res }) => {
        if (res.code !== 0) {
          return false
        }
        this.linkTypeoptions = {
          ...this.linkTypeoptions,
          ...res.data.list
        }
      }).catch(() => { })
    },
    // 获取信息
    getInfo () {
      this.$http.get(`/business/bslinkinfo/${this.dataForm.id}`).then(({ data: res }) => {
        if (res.code !== 0) {
          return false
        }
        this.dataForm = {
          ...this.dataForm,
          ...res.data
        }
        this.quillEditor.root.innerHTML = this.dataForm.remark
        this.fileList = []
        if (this.dataForm.logoUrl !== null && this.dataForm.logoUrl !== '') {
          this.fileList.push({ name: this.dataForm.logoUrl, url: window.SITE_CONFIG['apiURL'] + '/sys/oss/localhostDownload/' + this.dataForm.logoUrl, id: this.dataForm.id })
        }
        this.url = `${window.SITE_CONFIG['apiURL']}/sys/oss/fileupload?projectCode=link&projectName=网址链接信息&projectId=0&phase=0&ywTableName=bs_link_info&ywTableId=${this.dataForm.id}`
      }).catch(() => {})
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        this.$http[!this.dataForm.id ? 'post' : 'put']('/business/bslinkinfo/', this.dataForm).then(({ data: res }) => {
          if (res.code !== 0) {
            return false
          }
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              this.visible = false
              this.$emit('refreshDataList')
            }
          })
        }).catch(() => {})
      })
    }, 1000, { 'leading': true, 'trailing': false }),
    handlePreview (file) {
      window.open(file.url)
    },
    handleRemove (file, fileList) {
      this.$http.get(`/sys/oss/delete/` + file.name).then(({ data: res }) => {
        if (res.code !== 0) {
          return false
        } else {
          this.fileList = []
          this.dataForm.logoUrl = ''
          this.$message.success('删除成功')
        }
      })
    },
    successHandle (response, file, fileList) {
      if (response.code !== 0) {
        this.fileList = []
        return this.$message.error(response.msg)
      } else {
        this.fileList = fileList
        this.dataForm.logoUrl = response.data.id
        this.$message.success('上传成功！')
      }
    },
    // 富文本编辑器
    quillEditorHandle () {
      this.quillEditor = new Quill('#J_quillEditor', {
        modules: {
          toolbar: this.quillEditorToolbarOptions
        },
        theme: 'snow'
      })
      // 监听内容变化，动态赋值
      this.quillEditor.on('text-change', () => {
        this.dataForm.remark = this.quillEditor.root.innerHTML
      })
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG && !isPNG) {
        this.$message.error('上传头像图片只能是 JPG / PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return (isJPG || isPNG) && isLt2M
    }
  }
}
</script>
<style lang="scss">
  .el-card{
    margin-bottom: 53px;
  }
  .temp-content {
    // padding: 24px;
    .titlename {
        width: 100%;
        height: 60px;
        display: -webkit-box;
        display: -ms-flexbox;
        display: flex;
        -webkit-box-pack: center;
        -ms-flex-pack: center;
        justify-content: center;
        -webkit-box-align: center;
        -ms-flex-align: center;
        align-items: center;
        font-weight: bold;
        border-bottom: 1px solid #e6e6e6;
        font-size: 20px;
        p{
          margin: 10px 0;
        }
    }
    .temp-line {
      padding-bottom: 32px;
    }
    .temp-line:after {
        position: absolute;
        right: 0;
        bottom: 0;
        content: "";
        display: block;
        clear: both;
        width: 100%;
        min-width: 100%;
        height: 1px;
        margin: 8px 0 24px;
        background: #e8e8e8;
    }
    .temp-form {
      position: relative;
      .temp-subtitle {
        font-size: 16px;
        color: #333;
        line-height: 29px;
        margin-bottom: 16px;
        font-weight: bold
      }
      .el-date-editor.el-input{
         width: auto !important;
      }
      .el-date-editor{
        max-width: 280px;
      }
      .el-input {
        max-width: 280px;
      }
      .el-date-editor--daterange{
        max-width: 240px;
      }
    }
  }
  .foot{
    width: 100%;
    background: #fff;
    position: fixed;
    bottom: 0;
    padding: 10px 0;
    border-top: 1px solid #ddd;
    background: #f9f9f9;
    text-align: center;
    left: 80px;
    z-index: 999;
    span{
      text-align: center;
    }
  }
  .btn{
    .el-input-group__append{
      color: #fff;
      background-color: #409eff;
      border-color: #409eff;
      padding: 0 8px;
    }
  }
  .el-loading-mask{
    z-index: 998 !important;
  }
</style>
